package com.baozhun.mall.common.widget.citypicker

import android.content.Context
import android.util.Log
import android.view.View
import com.baozhun.mall.common.R
import com.baozhun.mall.common.databinding.WidgetCityPikerLayoutBinding
import com.baozhun.mall.common.widget.dialog.BaseBottomPopupView
import com.baozhun.mall.common.model.bean.RegionInfo
import com.lxj.xpopupext.adapter.ArrayWheelAdapter

/**
 * @Title：
 * @Description：
 * @Author：xing.luo
 * @Since：2022/12/2
 * @Version：1.0.0
 */
class CityPicker(context: Context, val data: List<RegionInfo>, val city: String, val area: String): BaseBottomPopupView<WidgetCityPikerLayoutBinding>(context) {
    var cityIndex = 0
    var areaIndex = 0
    var areaAdapter: ArrayWheelAdapter<RegionInfo>? = null
    var mListener: OnCityPickerListener? = null
    override fun getImplLayoutId(): Int {
        return R.layout.widget_city_piker_layout
    }

    fun setListener(listener: OnCityPickerListener) {
        this.mListener = listener
    }

    private fun getIndexOfRegion(name: String, data: List<RegionInfo>): Int {
        for (index in 0 until (data.size)) {
            if (name == data[index].region_name) {
                return index
            }
        }
        return 0
    }

    override fun onCreate() {
        super.onCreate()
        if(data.isEmpty()) {
            dismiss()
            return
        }
        cityIndex = getIndexOfRegion(city, data)
        areaIndex = getIndexOfRegion(area, data[cityIndex].child)
        Log.e("TAG", "$cityIndex,$areaIndex")

        mBinding.options1.adapter = ArrayWheelAdapter<RegionInfo>(data)
        mBinding.options1.currentItem = cityIndex
        mBinding.options1.setCyclic(false)
        mBinding.options1.setOnItemSelectedListener {
            cityIndex = it
            areaIndex = 0
            setAreaAdapter()
        }
        setAreaAdapter()
    }

    private fun setAreaAdapter() {
        areaAdapter = ArrayWheelAdapter<RegionInfo>(data[cityIndex].child)
        mBinding.options2.adapter = areaAdapter
        mBinding.options2.currentItem = areaIndex
        mBinding.options2.setCyclic(false)
        mBinding.options2.setOnItemSelectedListener {
            areaIndex = it
        }
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when(v?.id) {
            R.id.btnCancel -> dismiss()
            R.id.btnConfirm -> {
                dismiss()
                if (mListener != null) {
                    mListener?.onPick(data[cityIndex].region_name, data[cityIndex].child[areaIndex].region_name)
                }
            }
        }
    }
}